//
//  ViewController.swift
//  19.1 scrollview
//
//  Created by 李煜 on 2024/6/26.
//

import UIKit

let aColor = UIColor.init(red: 117 / 255.0, green: 179 / 255.0, blue: 191 / 255.0, alpha: 0.4)
let bColor = UIColor.purple

class ViewController: UIViewController,UIScrollViewDelegate {
    //a是scrollview的子视图
    var a: UIView = UIView(frame: CGRectMake(0, 0, 200, 400))
    //b是a的子视图
    var b: UIView! = UIView(frame: CGRectMake(0, 50, 200, 50))
    
    var scroll: UIScrollView = UIScrollView(frame: CGRectMake(0, 100, 200, 200))
    
    override func viewDidLoad() {
        super.viewDidLoad()
        floatC()
    }
    //子视图浮动效果
    func floatC() {
        
        scroll.bounces = false
        view.addSubview(scroll)
        scroll.delegate = self
        scroll.backgroundColor = .systemRed
        
        scroll.addSubview(a)
        a.backgroundColor = aColor
               
        a.addSubview(b)
        b.backgroundColor = bColor
        
        scroll.contentSize = CGSizeMake(200, 400)
    }
    
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print(scrollView.contentOffset)
        let offsetHeight = 50.0
        print(b.superview == scrollView)
//        switch方式
        switch  scrollView.contentOffset.y {
            case 0 ..< offsetHeight:
                if b.superview == a { return }
                b.removeFromSuperview()
                a.addSubview(b)
                b.frame = CGRectMake(0, 50, 200, 50)
            case offsetHeight...:
                if b.superview === view { return }
                b.removeFromSuperview()
                view.addSubview(b)
                b.frame = CGRectMake(scrollView.frame.minX, scrollView.frame.minY, 200, 50)
            default: break
        }
        
//        if方式
        
//        if scrollView.contentOffset.y >= offsetHeight  {
//            if b.superview == view {return}
//            b.removeFromSuperview()
//            view.addSubview(b)
//            b.frame = CGRectMake(0, 100, 200, 50)
//        }else  {
//            if b.superview == a {return}
//            b.removeFromSuperview()
//            a.addSubview(b)
//            b.frame = CGRectMake(0, 50, 200, 50)
//        }
        
        
    }


}

